package com.hyjx.framework.common;

import com.hyjx.framework.service.CaptchaService;
import com.hyjx.framework.service.SessionManager;
import org.patchca.color.ColorFactory;
import org.patchca.font.RandomFontFactory;
import org.patchca.service.Captcha;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.text.renderer.TextRenderer;
import org.patchca.word.RandomWordFactory;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 验证码生成类
 * <p>
 * 使用开源验证码项目patchca生成
 * 依赖jar包：patchca-0.5.0.jar
 * 项目网址：https://code.google.com/p/patchca/
 *
 * @author zyh
 * @version 1.00  2012-7-12 New
 */
@WebServlet(urlPatterns = {"/checkcode"})
public class CaptchaServlet extends HttpServlet {
    private static final long serialVersionUID = 5126616339795936447L;
    
    private ConfigurableCaptchaService configurableCaptchaService = null;
    private ColorFactory colorFactory = null;
    private RandomFontFactory fontFactory = null;
    private RandomWordFactory wordFactory = null;
    private TextRenderer textRenderer = null;
    
    public CaptchaServlet() {
        super();
    }
    
    /**
     * Servlet销毁方法,负责销毁所使用资源. <br>
     */
    @Override
    public void destroy() {
        wordFactory = null;
        colorFactory = null;
        fontFactory = null;
        textRenderer = null;
        configurableCaptchaService = null;
        super.destroy(); // Just puts "destroy" string in log
    }
    
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("image/png");
        response.setHeader("cache", "no-cache");
        OutputStream outputStream = response.getOutputStream();
        Captcha captcha = CaptchaService.getCaptcha();
        String validationCode = captcha.getChallenge();
        SessionManager.setByRequest(request, Constants.VALIDATIONCODE, validationCode);
        //request.getSession().setAttribute(Constants.VALIDATIONCODE, validationCode);
        BufferedImage bufferedImage = captcha.getImage();
        ImageIO.write(bufferedImage, "png", outputStream);
        outputStream.flush();
        outputStream.close();
    }
    
    /**
     * Servlet初始化方法
     */
    public void init() {
    
    }
}
